<template>
  <!-- 页面容器 -->
  <div class="app-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar-top">
      <!-- 左侧搜索区域 -->
      <div class="left">
        <!-- 搜索输入框 -->
        <el-input
          v-model="queryTableDataParams.keyword"
          placeholder="请输入搜索内容"
          class="search-input"
        />
        <!-- 搜索按钮 -->
        <el-button type="primary" @click="fetchTableData">搜索</el-button>
        <!-- 重置按钮 -->
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <!-- 右侧操作按钮区域 -->
      <div class="right">
        <!-- 新建指标域按钮 -->
        <el-button type="primary" @click="handleCreateIndicatorDomain">新建指标域</el-button>
        <!-- 删除按钮 -->
        <el-button type="danger" @click="handleDeleteTableData">删除</el-button>
        <!-- 新建数据源按钮 -->
        <el-button type="primary" @click="handleCreateDataSource">新建数据源</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择框列 -->
        <el-table-column type="selection" width="50" align="center" />
        <!-- 数据源名称 -->
        <el-table-column prop="aliasName" label="数据源名称" min-width="130" align="center" />
        <!-- 数据连接名称列 -->
        <el-table-column prop="dataSourceName" label="数据库名称" min-width="130" align="center" />
        <!-- 创建者列 -->
        <el-table-column prop="createUser" label="创建者" align="center" />
        <!-- 数据源类型列 -->
        <el-table-column prop="dataSourceType" label="数据源类型" align="center" />
        <!-- 服务地址列 -->
        <el-table-column prop="dataSourceAddress" label="服务地址" align="center" />
        <!-- 端口列 -->
        <el-table-column prop="dataSourcePort" label="端口" min-width="80" align="center" />
        <!-- 数据库列 -->
        <!-- <el-table-column prop="database" label="数据库" align="center" /> -->
        <!-- 数据源用户名列 -->
        <el-table-column prop="dataSourceUserName" label="数据源用户名" align="center" />
        <!-- 创建时间列 -->
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <!-- 描述列 -->
        <el-table-column prop="dataSourceDescription" label="描述" min-width="130" align="center" />
        <!-- 操作列 -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <!-- 测试按钮 -->
            <el-button type="primary" size="small" @click="handleInlineTest(row)">测试</el-button>
            <!-- 引用按钮 -->
            <!-- <el-button type="success" size="small" @click="handleInlineReference(row)">
              引用
            </el-button> -->
            <el-button type="success" size="small" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-if="tableDataTotal > 0"
        v-model:total="tableDataTotal"
        v-model:page="queryTableDataParams.pageIndex"
        v-model:limit="queryTableDataParams.pageSize"
        @pagination="fetchTableData"
      />
    </div>
    <el-dialog v-model="dialogVisible" title="新建指标域" width="600px" destroy-on-close>
      <create-indicator-field
        mode="domain"
        @success="handleDialogSuccess"
        @close="dialogVisible = false"
      />
    </el-dialog>
    <el-dialog v-model="dataSourceDialogVisible" title="新建数据源" width="600px" destroy-on-close>
      <create-data-source
        mode="dataSource"
        @success="handleDataSourceDialogSuccess"
        @close="dataSourceDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onActivated } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DataSourceAPI, { tableDataPageQuery, tableDataPageV0 } from "@/api/dataSourceManage";
import NewDataSourceAPI, { DeleteParameter } from "@/api/dataSourceManage/createDataSource";
import CreateIndicatorField from "@/views/dataSourceManage/component/createIndicatorField.vue";
import CreateDataSource from "@/views/dataSourceManage/component/createDataSource.vue"; // 引入新建数据源的组件
// 组件选项配置
defineOptions({
  name: "DataSourceManage",
  inheritAttrs: false,
});

// 对话框显示状态
const dialogVisible = ref(false);
const dataSourceDialogVisible = ref(false); // 新建数据源对话框显示状态
// 表格数据
const tableData = ref<tableDataPageV0[]>();
// 数据总条数
const tableDataTotal = ref(0);
// 表格加载状态
const tableDataLoading = ref(false);
// 表格查询参数
const queryTableDataParams = reactive<tableDataPageQuery>({
  pageIndex: 1,
  pageSize: 10,
});

const deleteParameter = reactive<DeleteParameter>({});

// 获取表格数据
function fetchTableData() {
  tableDataLoading.value = true;
  DataSourceAPI.tableDataQuery(queryTableDataParams)
    .then((data) => {
      data.data.forEach((item) => {
        if (item.dataSourceType == "1") {
          item.dataSourceType = "MySQL";
        } else if (item.dataSourceType == "2") {
          item.dataSourceType = "Oracle";
        }
      });
      tableData.value = data.data;
      tableDataTotal.value = data.total;
    })
    .finally(() => {
      tableDataLoading.value = false;
    });
}

// 重置搜索条件
function resetSearch() {
  queryTableDataParams.pageIndex = 1;
  queryTableDataParams.pageSize = 10;
  fetchTableData();
}

// 表格删除加载状态
const deleteTableDataLoading = ref(false);
// 表格选中行数据
const tableDataSelectedRows = ref([]);

// 处理表格选中行变化
const handleSelectionChange = (selection: any) => {
  tableDataSelectedRows.value = selection;
};

// 删除表格数据
function handleDeleteTableData() {
  deleteTableDataLoading.value = true;
  if (tableDataSelectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的项！");
    return;
  }
  const deleteData = tableDataSelectedRows.value.map((row) => ({
    id: row.id,
    type: row.type,
  }));
  ElMessageBox.confirm("确定要删除选中的数据吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      DataSourceAPI.deleteTableDataQuery(deleteData);
      resetSearch();
    })
    .finally(() => {
      deleteTableDataLoading.value = false;
    });
}

// 表格测试加载状态
const inlineTestLoading = ref(false);

// 处理行内测试
async function handleInlineTest(row: any) {
  inlineTestLoading.value = true;
  // DataSourceAPI.inlineTestQuery(row, tableData[row].type)
  //   .then((data) => {
  //     if (data.result === 1) {
  //       ElMessage.success("测试成功");
  //     } else {
  //       ElMessage.error("测试失败");
  //     }
  //   })
  //   .finally(() => {
  //     inlineTestLoading.value = false;
  //   });
  deleteParameter.id = row.id;
  try {
    await NewDataSourceAPI.test(deleteParameter);
    ElMessage.success("数据源连接成功");
  } catch (error) {
    ElMessage.error("数据源连接失败");
  }
}

// 处理行内引用
const handleInlineReference = (row: any) => {
  console.log(row);
};

const deleteRow = async (row: any) => {
  deleteParameter.id = row.id;
  try {
    await NewDataSourceAPI.delete(deleteParameter);
    fetchTableData(); // 删除成功后刷新表格数据
    ElMessage.success("删除成功");
  } catch (error: any) {
    ElMessage.error(`删除失败: ${error.message}`);
  }
};

// 处理新建指标域
function handleCreateIndicatorDomain() {
  dialogVisible.value = true;
}

// 处理新建数据源
function handleCreateDataSource() {
  dataSourceDialogVisible.value = true; // 显示新建数据源对话框
}

// 处理对话框提交成功
const handleDialogSuccess = () => {
  dialogVisible.value = false;
  fetchTableData(); // 刷新表格数据
  ElMessage.success("创建成功");
};

// 处理新建数据源对话框提交成功
const handleDataSourceDialogSuccess = () => {
  dataSourceDialogVisible.value = false;
  fetchTableData(); // 刷新表格数据
  ElMessage.success("创建成功");
};

// 组件挂载时获取表格数据
onMounted(() => {
  fetchTableData();
});
</script>

<style scoped lang="scss">
.toolbar-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18px 10px;
  margin-bottom: 10px;
  background-color: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);

  .left {
    display: flex;
    gap: 10px;
    align-items: center;
  }

  .search-input {
    width: 200px;
  }

  .right {
    display: flex;
    gap: 10px;
  }
}

.table-container {
  padding: 18px 10px;
  margin-bottom: 10px;
  background-color: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}
</style>
